//主面板的IPC事件
const {
	ipcMain,
	Notification,
	BrowserWindow,
	app,
	screen,
} = require("electron");
const path = require("node:path");
const {
	getData: getModuleData,
	saveData: saveModuleData,
} = require("./storage");

//是否是测试环境
const isDevelopment = !app.isPackaged;

//本线程永久循环任务
let intervalTask = undefined;
//窗口实时句柄
let mainHandler = undefined;
//角标句柄
let cornerHandler = undefined;
//倒计时池
let countdown = 0;
//上次计时总数
let countdownCache = 0;
//角标窗口
let cornerWindow = undefined;
//状态
let status = false;

/**
 * 定义IPC监听
 * TOMATO-INIT : 初始化主窗口句柄
 * TOMATO-CORNER-INIT : 初始化角标句柄
 * TOMATO-START : 开启新的计时
 * TOMATO-STOP : 中止计时
 * TOMATO-CORNER-VISIABLE : 切换角标是否显示
 * TOMATO-CLEAR-LIST : 清空番茄列表
 */
module.exports = () => {
	//初始化角标窗口
	initCornerWindow();

	//初始化循环计时任务
	intervalTask = setInterval(async () => {
		let resTime = undefined;
		const time = await getData("time");
		if (countdown === 0) {
			//没有计时任务，返回设置时间
			resTime = time * 60 * 1000;
			status = false;
		} else {
			//有计时任务，减少时间后返回
			status = true;
			countdown -= 1000;
			if (countdown <= 0) {
				//任务结束
				await addTodayRecord(0);
				sendNotification();
				countdown = 0;
				status = false;
			}
			resTime = countdown;
		}
		mainHandler?.reply("TOMATO-CLOCK-CALL", { value: resTime, status });
		cornerHandler?.reply("TOMATO-CLOCK-CALL", { value: resTime, status });
	}, 1000);

	//异步：监听初始化，储存句柄
	ipcMain.on("TOMATO-INIT", function (event, arg) {
		mainHandler = event;
	});

	//异步：监听角标初始化，储存角标句柄
	ipcMain.on("TOMATO-CORNER-INIT", function (event, arg) {
		cornerHandler = event;
	});

	//同步：监听开始计时
	ipcMain.on("TOMATO-START", async (event, arg) => {
		if (countdown !== 0) {
			//有未完成计时，结束
			event.returnValue = { error: "存在计时任务！" };
			return;
		}
		countdownCache = countdown = (await getData("time")) * 60 * 1000;
		event.returnValue = { error: 0 };
	});

	//同步：监听结束计时
	ipcMain.on("TOMATO-STOP", async function (event, arg) {
		if (countdown === 0) {
			//本来没有计时，结束
			event.returnValue = { error: "不存在计时任务！" };
			return;
		}
		//手动结束
		await addTodayRecord(countdown);
		countdown = 0;
		event.returnValue = { error: 0 };
	});

	//异步：监听切换角标显示
	ipcMain.on("TOMATO-CORNER-VISIABLE", async function (event, arg) {
		const { show } = arg;
		await saveData("showCorner", show);
		if (show) {
			cornerWindow.show();
		} else {
			cornerWindow.hide();
		}
	});

	//异步：清空今日番茄列表
	ipcMain.on("TOMATO-CLEAR-LIST", function (event, arg) {
		clearRecord();
	});
};

//保存完成记录
const addTodayRecord = async (remainTime) => {
	//状态： 0未完成 1已完成
	const status = remainTime <= 0 ? 1 : 0;
	const data = {
		status,
		taskTime: countdownCache,
		realTime: countdownCache - remainTime,
		finishTime: new Date().getTime(),
	};
	const list = await getTodayRecord();
	list.unshift(data);
	saveData("todayList", list);
};

//获取今日完成记录
const getTodayRecord = async () => {
	let dataList = await getData("todayList");
	dataList = dataList ?? [];
	//排除日期
	const todayDate = new Date();
	const tyear = todayDate.getFullYear();
	const tmonth = todayDate.getMonth() + 1;
	const tday = todayDate.getDate();
	const butMils = new Date(`${tyear}-${tmonth}-${tday} 00:00:00`);
	return dataList.filter((e) => e.finishTime >= butMils);
};

//清除记录
const clearRecord = () => {
	saveData("todayList", []);
};

//发送系统通知
const sendNotification = () => {
	new Notification({
		title: "番茄钟任务完成",
		body: "提醒您注意身体健康，多喝水，适当运动。",
		urgency: "critical",
		timeoutType: "never",
		icon: path.join(__dirname, "../assets/PlantB.ico"),
	}).show();
};

//定制番茄钟的角标
const initCornerWindow = async () => {
	//判断设置钟是否显示角标
	const show = await getData("showCorner");
	// 获取应用窗口的边界，通常不包括任务栏高度
	const screenWidth = screen.getPrimaryDisplay().bounds.width;
	cornerWindow = new BrowserWindow({
		x: screenWidth - 50,
		y: 1000,
		focusable: false,
		width: 50,
		height: 25,
		titleBarStyle: "hidden",
		resizable: false,
		minimizable: false,
		maximizable: false,
		closable: false,
		alwaysOnTop: true,
		transparent: true,
		webPreferences: {
			preload: path.join(__dirname, "../preload.js"),
		},
		show,
	});
	// cornerWindow.webContents.openDevTools();
	if (isDevelopment) {
		cornerWindow.loadURL(
			path.join("http://localhost:7758", "clock_tomato/corner")
		);
	} else {
		cornerWindow.loadFile(path.join(__dirname, "../platform/index.html"), {
			hash: "clock_tomato/corner",
		});
	}
	cornerWindow.setAlwaysOnTop(true, "normal");
	//隐藏任务栏
	cornerWindow.setSkipTaskbar(true);
};

//获取设置数据
const getData = async (key) => {
	const data = await getModuleData("tomato");
	return data[key];
};

//保存设置数据
const saveData = async (key, value) => {
	const data = {};
	data[key] = value;
	await saveModuleData(data, "tomato");
};
